package com.black.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.black.common.constant.CacheConstants;
import com.black.common.exception.ServiceException;
import com.black.common.exception.database.PrimaryException;
import com.black.common.exception.database.RecordNotFoundException;
import com.black.common.utils.MessageUtils;
import com.black.system.domain.SysConfig;
import com.black.system.domain.req.sysconfig.SysConfigAddReq;
import com.black.system.domain.req.sysconfig.SysConfigEditReq;
import com.black.system.domain.req.sysconfig.SysConfigQueryReq;
import com.black.system.domain.resp.sysconfig.SysConfigResp;
import com.black.system.mapper.SysConfigMapper;
import com.black.system.service.SysConfigService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @author Administrator
 * @description 针对表【sys_config(参数配置表)】的数据库操作Service实现
 * @createDate 2024-08-19 10:07:21
 */
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig>
        implements SysConfigService {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 根据key获取配置值
     *
     * @return
     */
    @Override
    public String getConfigValueByKey(String configKey) {
        //做redis缓存的查询
        if (redisTemplate.hasKey(CacheConstants.SYS_CONFIG_KEY + configKey)) {
            return (String) redisTemplate.opsForValue().get(CacheConstants.SYS_CONFIG_KEY + configKey);
        }
        // 创建一个查询对象 select * from sys_config
        LambdaQueryWrapper<SysConfig> queryWrapper = new LambdaQueryWrapper<>();
        //条件构造器  https://baomidou.com/guides/wrapper/#ge
        queryWrapper.eq(SysConfig::getConfigKey, configKey);
        //执行查询，获取结果
        SysConfig sysConfig = this.getOne(queryWrapper);
        //查询不到
        if (Objects.isNull(sysConfig)) {
            return StrUtil.EMPTY;
        }
        // 数据库中配置了黑白单的
        if (StrUtil.isNotBlank(sysConfig.getConfigValue())) {
            //存入到redis中
            redisTemplate.opsForValue().set(CacheConstants.SYS_CONFIG_KEY + sysConfig.getConfigKey(), sysConfig.getConfigValue());
            return sysConfig.getConfigValue();
        }

        //存入到redis中(值为"")
        redisTemplate.opsForValue().set(CacheConstants.SYS_CONFIG_KEY + sysConfig.getConfigKey(), StrUtil.EMPTY);
        return StrUtil.EMPTY;
    }

    /**
     * 分页查询
     *
     * @param req
     * @return
     */
    @Override
    public PageInfo<SysConfigResp> paginationQuery(SysConfigQueryReq req) {

        return PageHelper.startPage(req.getPageNum(), req.getPageSize()).doSelectPageInfo(() -> {
            //调用sysConfigMapper[mybatis]，要么使用LamdbaQueryWrapper来写[mybatis-plus]
            // 一定返回的结是 List<SysConfigResp>
            this.baseMapper.paginationQuery(req);
        });
    }

    // 新增
    @Override
    public boolean add(SysConfigAddReq req) {

        // 校验 req.getConfigKey() 是否已经存在
        if (this.baseMapper.exists(new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getConfigKey, req.getConfigKey()))) {
            throw new ServiceException(MessageUtils.message("sysconfig.configKey.exists"));
        }

        SysConfig newEntity = new SysConfig();
//        newEntity.setConfigName(req.getConfigName());
//        newEntity.setConfigKey(req.getConfigKey());
//        newEntity.setConfigType(req.getConfigType());
//        newEntity.setConfigValue(req.getConfigValue());
//        newEntity.setRemark(req.getRemark());

        // 对象拷贝
        BeanUtils.copyProperties(req, newEntity);

//        newEntity.setCreateBy(SecurityUtils.getUsername());
//        newEntity.setCreateTime(new Date());

        boolean save = this.save(newEntity);
        if (save) {
            //清空缓存
            redisTemplate.opsForValue().set(CacheConstants.SYS_CONFIG_KEY + req.getConfigKey(), newEntity);
        }

        return save;
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public SysConfigResp findById(Long id) {
        if (Objects.isNull(id)) {
            throw new PrimaryException();
        }
        // 根据主键查询
        SysConfig sysConfig = this.getById(id);
        if (Objects.isNull(sysConfig)) {
            throw new RecordNotFoundException();
        }

        // 封装响应对象
        SysConfigResp resp = new SysConfigResp();
        BeanUtils.copyProperties(sysConfig, resp);
        return resp;
    }

    // 修改
    @Override
    public boolean edit(SysConfigEditReq req) {
        // 根据id查询
        SysConfig sysConfig = this.getById(req.getConfigId());
        // 判断 查不到数据
        if (Objects.isNull(sysConfig)) {
            throw new RecordNotFoundException();
        }

        // 验证configKey是否已经存在
        if (!req.getConfigKey().equals(sysConfig.getConfigKey())) {
            if (this.baseMapper.exists(new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getConfigKey, req.getConfigKey()))) {
                throw new ServiceException(MessageUtils.message("sysconfig.configKey.exists"));
            }
        }
        sysConfig.setUpdateBy(null);
        sysConfig.setUpdateTime(null);
        // 更新
        BeanUtils.copyProperties(req, sysConfig);

        boolean res = this.updateById(sysConfig);
        if (res) {
            redisTemplate.opsForValue().set(CacheConstants.SYS_CONFIG_KEY + req.getConfigKey(), sysConfig);
        }

        return res;
    }

    /**
     * 根据id删除
     *
     * @param ids
     * @return
     * @Transactional 事务
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteById(Long[] ids) {

        final SysConfigServiceImpl sysConfigService = this;

        if (Objects.isNull(ids) || ids.length == 0) {
            throw new PrimaryException();
        }

        this.redisTemplate.execute(new SessionCallback<Void>() {
            @Override
            public Void execute(RedisOperations operations) throws DataAccessException {
                // 开启redis事务
                operations.multi();

                // 循环删除，因为数据量不大, 时间复杂度O(n), 事务问题
                try {
                    for (Long id : ids) {
                        SysConfig db = sysConfigService.getById(id);
                        if (Objects.nonNull(db)) {
                            //删除数据库中的值
                            sysConfigService.removeById(id);
                            //移出缓存中的值
                            String redisKey = CacheConstants.SYS_CONFIG_KEY + db.getConfigKey();
                            operations.delete(redisKey);
                        }
                    }
                    // 提交redis事务
                    operations.exec();

                } catch (Exception e) {
                    operations.discard();
                    throw e;
                }
                return null;
            }
        });

        return true;
    }

    /**
     * 导出
     *
     * @param req
     * @param ids
     * @return
     */
    @Override
    public List<SysConfigResp> export(SysConfigQueryReq req, Long[] ids) {
        List<SysConfigResp> dataList;
        // 根据主键导出
        if (Objects.nonNull(ids) && ids.length > 0) {
            dataList = this.baseMapper.exportByIds(ids);
        } else {
            //按条件查询
            dataList = this.baseMapper.paginationQuery(req);
        }

        return dataList;
    }


}




